
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.Repositories;
using Abp.UI;
using Abp.UI.Inputs;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.Helper;
using SOEI.Solution.StructEntities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;


namespace SOEI.Solution.DomainEntities.PurQualificationAudit.DomainService
{
    /// <summary>
    /// 领域服务层一个模块的核心业务逻辑
    ///</summary>
    public class PurQualificationApplyManager : DomainServiceBase, IPurQualificationApplyManager
    {
        // 购资审核 领域服务
        private readonly IRepository<PurQualificationApply, string> _purqualificationapplyRepository;

        /// <summary>
        /// 【Parameter】参数的领域服务
        /// </summary>
        private readonly IParameterManager _parameterManager;

        /// <summary>
        /// 【PurQualificationApply】的构造方法
        /// 通过构造函数注册服务到依赖注入容器中
        ///</summary>
        public PurQualificationApplyManager(IRepository<PurQualificationApply, string> purqualificationapplyRepository,
            IParameterManager parameterManager)
        {
            _purqualificationapplyRepository = purqualificationapplyRepository;
            _parameterManager = parameterManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        /// 返回列表查询用
        /// </summary>
        /// <returns></returns>
        public IQueryable<PurQualificationApply> QueryEntityListAsNoTracking()
        {

            var query = _purqualificationapplyRepository.GetAll().AsNoTracking()
                        .Select(x => new PurQualificationApply
                        {

                            Id = x.Id,
                            GFRLXDM = x.GFRLXDM,
                            GFRXM = x.GFRXM,
                            ZJMC = x.ZJMC,
                            ZJHM = x.ZJHM,
                            LXDH = x.LXDH,
                            NGZFDZ = x.NGZFDZ,
                            HJSZD = x.HJSZD,
                            JTYYZFQK = x.JTYYZFQK,
                            LRSJ = x.LRSJ,
                            SXSJ = x.SXSJ,
                            SQZTDM = x.SQZTDM,
                            FWBH = x.FWBH,
                            HTDJH = x.HTDJH,
                            SM = x.SM,
                            YWLXDM = x.YWLXDM,
                            DWBH = x.DWBH,
                            LRRBH = x.LRRBH,
                            LRRXM = x.LRRXM,
                            QYDM = x.QYDM,
                            XGLX = x.XGLX,
                            ZLSCZTDM = x.ZLSCZTDM,
                            ISBS = x.ISBS,
                            SCRBH = x.SCRBH,
                            SCRXM = x.SCRXM,
                            SCSJ = x.SCSJ,
                            ZLSCFSDM = x.ZLSCFSDM,
                            XGRBH = x.XGRBH,
                            XGRMC = x.XGRMC,
                            XGSJ = x.XGSJ,
                            SFDC = x.SFDC,
                            WTHTJGBH = x.WTHTJGBH,
                            TJSJ = x.TJSJ,
                            //过期时间
                            GQSJ = x.GQSJ,
                            //数据来源
                            SJLY = x.SJLY,
                        });
            return query;
        }

        /// <summary>
        /// 【PurQualificationApply】返回表达式数的实体信息即IQueryable类型
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<PurQualificationApply> Query()
        {
            return _purqualificationapplyRepository.GetAll();
        }
        /// <summary>
        /// 【PurQualificationApply】返回即IQueryable类型的实体，不包含EF Core跟踪标记
        /// </summary>
        /// <returns>IQueryable</returns>
        public IQueryable<PurQualificationApply> QueryAsNoTracking()
        {
            return _purqualificationapplyRepository.GetAll().AsNoTracking();
        }
        /// <summary>
        /// 【PurQualificationApply】根据Id查询实体信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns>实体</returns>
        public async Task<PurQualificationApply> FindByIdAsync(string id)
        {
            var entity = await _purqualificationapplyRepository.GetAsync(id);
            return entity;
        }
        /// <summary>
        /// 【PurQualificationApply】检查实体是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns>bool</returns>
        public async Task<bool> IsExistAsync(string id)
        {
            var result = await _purqualificationapplyRepository.GetAll().AnyAsync(a => a.Id == id);
            return result;
        }
        /// <summary>
        /// 【PurQualificationApply】创建实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PurQualificationApply> CreateAsync(PurQualificationApply entity)
        {
            entity.Id = await _purqualificationapplyRepository.InsertAndGetIdAsync(entity);
            return entity;
        }
        /// <summary>
        /// 【PurQualificationApply】更新实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        public async Task UpdateAsync(PurQualificationApply entity)
        {
            await _purqualificationapplyRepository.UpdateAsync(entity);
        }
        /// <summary>
        /// 【PurQualificationApply】删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(string id)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _purqualificationapplyRepository.DeleteAsync(id);
        }
        /// <summary>
        /// 【PurQualificationApply】批量删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BatchDelete(List<string> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _purqualificationapplyRepository.DeleteAsync(a => input.Contains(a.Id));
        }
        #endregion


        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展领域服务接口*/
        //public PurQualificationApply GetInfo()
        //{
        //    var entity = new PurQualificationApply()
        //    {
        //        //获取新的序列号
        //        Id = GetNewSequenceCode(),
        //        //购房人人员类型为个人
        //        GFRLXDM = "01",
        //        //数据来源于新模式--与旧系统做区分
        //        SJLY = "XMS",
        //        //业务类型代码为JJD
        //        YWLXDM = "JJD",
        //        //申请状态代码为01--未提交
        //        SQZTDM = "01",
        //        //录入时间
        //        LRSJ = System.DateTime.Now,
        //    };
        //    return entity;
        //}

        #region 检查家庭成员是否在黑名单中
        public async Task<string> Check_JTCYinHMD(List<PurFamilyVerifyS> purFamilyVerifyS)
        {
            try
            {
                string resJson = "";
                string flag = "true";//表示查询成功
                string res = "";
                var vCheckModelJson = BusinessUtils.ObjectToJson(purFamilyVerifyS).ToString();

                string jsonJtcy = BusinessUtils.UpperFirst(vCheckModelJson);

                string fmt = "{\"tName\":" + jsonJtcy + "}";

                DataSet dsJtcy = JsonConvert.DeserializeObject<DataSet>(fmt);


                if (dsJtcy != null)
                {
                    string xmlJtcy = BusinessUtils.DataTable2Xml(dsJtcy.Tables[0]);

                    if (string.IsNullOrEmpty(xmlJtcy))
                    {
                        flag = "false";
                        res = "申请人或家庭成员填写有误";
                    }
                    else
                    {
                        string bzInfo = "";
                        //FGXT_YW.PKG_XGL.Sp_Get_Gfzgsqzt.SP_GET_FGZGSQINFO 查询详细信息
                        //FGXT_YW.PKG_XGL.Sp_Get_Gfzgsqzt
                        //FGXT_YW.PKG_XGL.Sp_Get_Ysyjxx
                        //Sp_Get_GfzgTxList.Sp_Get_GfzgTxList  获取图像信息列表

                        //Sp_IsXGBMD--提交审核--检测是否在限购白名单
                        //SP_FINDQYKGGL --通过购房资格申请编号查询查询西安房产开关是否开启
                        //FGXT_YW.PKG_XGL_LEAVEUP.Sp_CHECK_GSTX --检查上传图像信息
                        //FGXT_YW.PKG_XGL.Sp_Get_Ysyjxx --获取应收要件信息
                        var vTestParam = ParamCollect.FromObj(new
                        {
                            IC_JTCY = xmlJtcy,

                        }, ParameterDirection.Input);

                        DataSet ds = await _purqualificationapplyRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_XGL.SP_CHECK_JTCYINHMD", vTestParam, "CURSOR");

                        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                        {
                            bzInfo = ds.Tables[0].Rows[0][0].ToString();
                        }
                        return bzInfo;
                    }
                }
                else
                {
                    flag = "false";
                    res = "申请人或家庭成员填写有误";
                }

                resJson = "{\"flag\":\"" + flag + "\",\"msg\":\"" + res + "\"}";
                //Response.Write(resJson);
                //Response.End();

                return resJson;
            }
            catch (System.Threading.ThreadAbortException)
            { }
            catch (Exception ex)
            {
                string resJson = "{\"flag\":\"false\",\"msg\":\"校验失败，请联系管理员\"}";
                //Response.Write(resJson);
                //Response.End();
            }

            return null;
        }

        #endregion



        /// <summary>
        /// 【PurQualificationApply】更新实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<PurQualificationApply> MyUpdateAsync(PurQualificationApply entity)
        {
            var Entity = await _purqualificationapplyRepository.UpdateAsync(entity);
            return Entity;
        }

        #region 关联查询
        /// <summary>
        /// 通过关联查询获取外列表所需结果
        /// </summary>
        /// <returns></returns>
        public IQueryable<PurQualificationApply> QueryUnionEntityListAsNoTracking()
        {
            //获取申请状态参数
            var ListApplyStatusEntity = this._parameterManager.QueryApplyStatus().ToList();
            //获取审查状态参数
            //var ListMaterialAuditEntity = this._parameterManager.QueryMaterialAudit().ToList();
            //返回列表查询用
            var query = this.QueryEntityListAsNoTracking()
                .Where(a => a.SJLY.Equals("XMS"));

            var count = query.CountAsync();
            //联合查询
            var Result = from x in query
                         join a in ListApplyStatusEntity on x.SQZTDM equals a.Id into dc
                         from dci in dc.DefaultIfEmpty()
                         select new PurQualificationApply
                         {

                             Id = x.Id,
                             GFRLXDM = x.GFRLXDM,
                             GFRXM = x.GFRXM,
                             ZJMC = x.ZJMC,
                             ZJHM = x.ZJMC,
                             LXDH = x.LXDH,
                             NGZFDZ = x.NGZFDZ,
                             HJSZD = x.HJSZD,
                             JTYYZFQK = x.JTYYZFQK,
                             LRSJ = x.LRSJ,
                             SXSJ = x.SXSJ,
                             SQZTDM = x.SQZTDM,
                             FWBH = x.FWBH,
                             HTDJH = x.HTDJH,
                             SM = x.SM,
                             YWLXDM = x.YWLXDM,
                             DWBH = x.DWBH,
                             LRRBH = x.LRRBH,
                             LRRXM = x.LRRXM,
                             QYDM = x.QYDM,
                             XGLX = x.XGLX,
                             ZLSCZTDM = x.ZLSCZTDM,
                             ISBS = x.ISBS,
                             SCRBH = x.SCRBH,
                             SCRXM = x.SCRXM,
                             SCSJ = x.SCSJ,
                             ZLSCFSDM = x.ZLSCFSDM,
                             XGRBH = x.XGRBH,
                             XGRMC = x.XGRMC,
                             XGSJ = x.XGSJ,
                             SFDC = x.SFDC,
                             WTHTJGBH = x.WTHTJGBH,
                             TJSJ = x.TJSJ,
                             //过期时间
                             GQSJ = x.GQSJ,
                             //数据来源
                             SJLY = x.SJLY,
                             //审查状态
                             //ApplyStatus = dci.Value
                         };
            return Result;
        }
        #endregion


        /// <summary>
        /// 获取新的购资审核申请编号
        /// </summary>
        /// <returns></returns>
        public string GetNewSequenceCode()
        {
            var code = this.GetSequence().ToString();
            code = code.PadLeft(8, '0');
            return "GS" + code;
        }

        /// <summary>
        /// 获取新的购资审核申请编号
        /// </summary>
        /// <returns></returns>
        private object GetSequence()
        {
            var sql = string.Format("select {0}.Nextval from dual", "SEQ_GFZGSCSQBH");
            return _purqualificationapplyRepository.GetDbContext().Database.ExecuteScalar(sql);
        }

        /// <summary>
        /// 获取新的家庭成员信息表编号
        /// </summary>
        /// <returns></returns>
        public string GetSonNewSequenceCode()
        {
            var code = this.GetSonSequence().ToString();
            return code.PadLeft(10, '0');
        }

        /// <summary>
        /// 获取新的家庭成员信息表编号
        /// </summary>
        /// <returns></returns>
        private object GetSonSequence()
        {
            var sql = string.Format("select {0}.Nextval from dual", "SEQ_GFZGSCSQJTCYBH");
            return _purqualificationapplyRepository.GetDbContext().Database.ExecuteScalar(sql);
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task SubmitAudit(string Id)
        {
            var result = await this.IsExistAsync(Id);
            if (result == false)
            {
                throw new UserFriendlyException("对应信息不存在!");
            }
            var key = Id;
            var entity = await _purqualificationapplyRepository.GetAsync(key);

            //校验购房资格申请对应的家庭成员是否在购房资格审查黑名单中
            Check_GFZGCYinHMD(Id);

            //不是白名单，要调接口查询西安房产数据
            if (IsXGBMD(Id) != "1")
            {
                string strZFQK = "";
                //判断西安房产接口查询开关是否开启
                DataSet ds_kg = await FINDQYKGGL(Id);
                var CXXAFCKG = "0";
                if (ds_kg != null && ds_kg.Tables[0] != null && ds_kg.Tables[0].Rows.Count > 0)
                {
                    CXXAFCKG = ds_kg.Tables[0].Rows[0]["SPFDYXAFC"].ToString();  //==0
                }
                if (CXXAFCKG == "1")
                {
                    string sfzhlist = "";

                    DataSet vDs = await GetSetZGSCSQBySQBH(Id);   //可以走查询GetbyId(GFZGSCSQBH)==替换

                    for (int i = 0; i < vDs.Tables[1].Rows.Count; i++)
                    {
                        sfzhlist += vDs.Tables[1].Rows[i]["ZJHM"].ToString().ToUpper() + ",";
                        if (vDs.Tables[1].Rows[i]["ZJLXDM"].ToString() == "10")  //身份证
                        {
                            sfzhlist += BusinessUtils.ConverCardId(vDs.Tables[1].Rows[i]["ZJHM"].ToString()).ToUpper() + ",";
                        }
                    }

                    sfzhlist = sfzhlist.TrimEnd(','); //删除尾部","
                    //调接口查询西安房产数据
                    string parameters = "{\"GFZGSQBH\":\"" + Id + "\",\"SFZHLIST\":\"" + sfzhlist + "\"}";
                    //string resFCCXJG = BusinessUtils.HttpPostJsonAPI(BusinessUtils.GETGSXAFCAPIUrl(), parameters, BusinessUtils.GetToken());
                    string resFCCXJG = BusinessUtils.HttpPostJsonAPI(JsonFile.TxmSettings.ApiUrl, parameters, JsonFile.TxmSettings.Token);  //获取api、token

                    ServiceEntity.GFZGFCResult resultJG = JsonConvert.DeserializeObject<ServiceEntity.GFZGFCResult>(resFCCXJG);

                    int p_SHJG;
                    //是否有经适房
                    if (resultJG.data.MJSFZG.ISYXZG && resultJG.data.MJSFZG.TotalNum == 0)
                    {
                        p_SHJG = -1;
                        //return "买受人或其所在家庭在西安已申请购买了经济适用住房，不能再次购买商品房！";
                        throw new UserFriendlyException("买受人或其所在家庭在西安已申请购买了经济适用住房，不能再次购买商品房!");
                    }
                    else if (resultJG.data.MJSFZG.QiutNum > 0)
                    {
                        p_SHJG = -1;
                        //return "买受人或其所在家庭在西安已拥有经适房购买资格，不能再次购买商品房！";
                        throw new UserFriendlyException("买受人或其所在家庭在西安已拥有经适房购买资格，不能再次购买商品房!");
                    }
                }
                //申请状态更改为审查中
                entity.SQZTDM = "02";
                //录入提交时间
                entity.TJSJ = System.DateTime.Now;

                await this.UpdateAsync(entity);
            }
        }

        /// <summary>
        /// 校验购房资格申请对应的家庭成员是否在购房资格审查黑名单中
        /// </summary>
        private async void Check_GFZGCYinHMD(string Id)
        {
            try
            {
                string resJson;
                string flag = "true";//表示查询成功
                string res;
                if (!string.IsNullOrEmpty(Id))
                {
                    res = await CheckGFZGCY_inHMD(Id);
                }
                else
                {
                    flag = "false";
                    res = "购房资格申请编号为空，请检查";
                    throw new UserFriendlyException(res);
                }
                resJson = "{\"flag\":\"" + flag + "\",\"msg\":\"" + res + "\"}";
            }
            catch (System.Threading.ThreadAbortException)
            { }
            catch (Exception ex)
            {
                string resJson = "{\"flag\":\"false\",\"msg\":\"校验失败，请联系管理员\"}";
            }
        }

        /// <summary>
        /// 校验购房资格申请对应的家庭成员是否在购房资格审查黑名单中
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task<string> CheckGFZGCY_inHMD(string id)
        {
            string bzInfo = "";
            DataSet ds = await CheckGFZGCY_inHMDAsync(id);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                bzInfo = ds.Tables[0].Rows[0][0].ToString();
            }
            return bzInfo;

        }

        /// <summary>
        /// 校验购房资格申请对应的家庭成员是否在购房资格审查黑名单中
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task<DataSet> CheckGFZGCY_inHMDAsync(string id)
        {
            var vTestParam = ParamCollect.FromObj(new
            {
                IS_GFZGSQBH = id,

            }, ParameterDirection.Input);

            DataSet ds = await _purqualificationapplyRepository.GetDbContext().Database.ExecuteStoreProcedure(" PKG_XGL.SP_CHECK_GFZGCYINHMD", vTestParam, "CURSOR");
            return ds;
        }

        /// <summary>
        /// 查询详细信息
        /// </summary>
        /// <param name="SQBH"></param>
        /// <returns></returns>
        public async Task<DataSet> GetSetZGSCSQBySQBH(string SQBH)
        {
            var parameter = ParamCollect.FromObj(new
            {
                IS_GFZGSCSQBH = SQBH,
            }, ParameterDirection.Input);

            DataSet ds = await _purqualificationapplyRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_XGL_LEAVEUP.SP_GET_FGZGSQINFO", parameter, "GFZGSCSQ", "GFZGSCSQMX");  //出参两个
            //DataSet ds = this.RunProcedure("PKG_XGL_LEAVEUP.SP_GET_FGZGSQINFO", Parameters, new ArrayList() { "GFZGSCSQ", "GFZGSCSQMX" });  
            if (ds.Tables[0].Rows.Count < 1)
                return null;
            else
                return ds;

        }

        /// <summary>根据购房编号查询区域开关是否开启   
        /// </summary>
        /// <param name="pGFZGSCSQBH"></param>
        /// <returns></returns>
        public async Task<DataSet> FINDQYKGGL(string pGFZGSCSQBH)
        {
            var parameter = ParamCollect.FromObj(new
            {
                IS_GFZGSCSQBH = pGFZGSCSQBH,
            }, ParameterDirection.Input);

            DataSet ds = await _purqualificationapplyRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_XGL.SP_FINDQYKGGL", parameter, "CURSOR");
            return ds;
        }

        /// <summary> 判断限购白名单
        /// </summary>
        /// <param name="pSQBH"></param>
        /// <returns></returns>
        public string IsXGBMD(string pSQBH)
        {
            var parameter = ParamCollect.FromObj(new
            {
                is_GFZGSQBH = pSQBH,

            }, ParameterDirection.Input);

            return _purqualificationapplyRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_XGL.Sp_IsXGBMD", parameter).ToString();

        }



        /// <summary>
        /// 获取新的购资审核变更信息表的序列
        /// </summary>
        /// <returns></returns>
        public string GetGSChangeSequence()
        {
            var code = this.GetGSSequence().ToString();
            return code.PadLeft(10, '0');
        }

        /// <summary>
        /// 获取新的购资审核变更信息表的序列
        /// </summary>
        /// <returns></returns>
        private object GetGSSequence()
        {
            var sql = string.Format("select {0}.Nextval from dual", "YW_GFZGSCSQBGXX_BH");
            return _purqualificationapplyRepository.GetDbContext().Database.ExecuteScalar(sql);
        }

        /// <summary>
        /// 获取家庭成员变更信息表的序列
        /// </summary>
        /// <returns></returns>
        public string GetJTChangeSequence()
        {
            var code = this.GetJTSequence().ToString();
            return code.PadLeft(10, '0');
        }

        /// <summary>
        /// 获取家庭成员变更信息表的序列
        /// </summary>
        /// <returns></returns>
        private object GetJTSequence()
        {
            var sql = string.Format("select {0}.Nextval from dual", "YW_GFZGSCSQBGXX_BH");
            return _purqualificationapplyRepository.GetDbContext().Database.ExecuteScalar(sql);
        }
        #endregion

    }


}
